package com.sdgs.paas.sdk.core.web;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import com.sdgs.paas.sdk.core.PaasBaseException;
import com.sdgs.paas.sdk.core.PaasBaseResponse;
import com.sdgs.paas.sdk.core.PaasDefaultObject;
import com.sdgs.paas.sdk.core.PaasResponseEnum;
import com.sdgs.paas.sdk.core.log.PaasLogger;

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class PaasGlobalHandlerExceptionResolver extends ResponseEntityExceptionHandler {

	@Autowired
	PaasHttpProperties paasHttpProperties;

	@ExceptionHandler({ Exception.class })
	public ResponseEntity<Object> handleAll(Exception ex, WebRequest request) {
		HttpHeaders headers = new HttpHeaders();
		HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
		// 纯粹是为了兼容之前的逻辑
		int exmod = paasHttpProperties.getExceptionMode();
		if (HttpStatus.OK.value() == exmod) {
			status = HttpStatus.OK;
		}
		return handleExceptionInternal(ex, null, headers, status, request);

	}

	@Override
	protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers,
			HttpStatus status, WebRequest request) {
		PaasLogger.error(ex, "Paas全局异常记录！");
		PaasBaseResponse<PaasDefaultObject> resp = new PaasBaseResponse<PaasDefaultObject>();
		PaasDefaultObject defaultObj = new PaasDefaultObject();
		defaultObj.setContent(ExceptionUtils.getStackTrace(ex));
		resp.setBody(defaultObj);
		if (ex instanceof PaasBaseException) {
			resp.setCode(((PaasBaseException) ex).getPaasExceptionCode());
			resp.setMsg(((PaasBaseException) ex).getPaasExceptionMsg());
		} else {
			resp.setCode(PaasResponseEnum.FAIL.code());
			resp.setMsg(PaasResponseEnum.FAIL.msg());
		}
		resp.setRequest_info(request.getDescription(true));
		resp.setException_msg(ex.getMessage());
		resp.setHttp_status(status.value());

		return new ResponseEntity<Object>(resp, headers, status);
	}

}
